package rs.networx.servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import rs.networx.dao.PersonDao;
import rs.networx.entity.Person;
import rs.networx.util.ErrorMessages;;

public class ActivationServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	@EJB
	private PersonDao personDao;
	
	private String personID;
	private String personActivstionCode;
	
	private Integer intPersonID;
	private Long longPersonActivationCode;
	
	private boolean activationStatus;
	
	private Person activatedPerson;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		System.out.println("SERVLET ACTIVATION: activaetd");
		
		response.setContentType("text/html; charset=UTF-8");
		request.setCharacterEncoding(response.getCharacterEncoding());
		
		HttpSession session = request.getSession(true);
		
		personID = request.getParameter("personID");
		personActivstionCode = request.getParameter("activationCode");
		
		intPersonID = Integer.parseInt(personID);
		longPersonActivationCode = Long.parseLong(personActivstionCode);
		
		System.out.println(intPersonID + " , " + longPersonActivationCode);
		
		activationStatus = personDao.activate(intPersonID, longPersonActivationCode);
		
		if(activationStatus == true){
			activatedPerson = personDao.findById(intPersonID);
			activatedPerson.setLoggedIn(true);
			
			System.out.println("Uspesno aktiviran: " + activatedPerson.getEmail());			
			session.setAttribute("logovaniUser", activatedPerson);
			
			request.getRequestDispatcher("WelcomePage.jsp").forward(request, response);
			return;
		}else if(activationStatus == false){
			session.setAttribute("loginStatus", ErrorMessages.LOGIN_FAILED);
			
			request.getRequestDispatcher("WelcomePage.jsp").forward(request, response);
			return;
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		doGet(request, response);
	}
	

}
